package com.woniu.cq.mallorder.consumer;

import com.woniu.cq.mallorder.service.IOrderService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author Daniel
 * @version 1.0.0
 * @ClassName OrderTransactionConsumer
 * @Description TODO
 * @createTime 2020年09月23日 22:57:00
 */
@Component
@RocketMQTransactionListener
public class OrderTransaction implements RocketMQLocalTransactionListener {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IOrderService orderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            Integer userId =Integer.parseInt(o.toString());
            int order = orderService.createOrder(userId);
            if (order>0){
                stringRedisTemplate.opsForValue().set("orderId",order+"");
                String statusId = message.getHeaders().get("statusId").toString();
                stringRedisTemplate.opsForValue().set(statusId,1+"");
                stringRedisTemplate.expire(statusId,5, TimeUnit.SECONDS);
                return RocketMQLocalTransactionState.COMMIT;
            }
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String statusId = message.getHeaders().get("statusId").toString();
        String s = stringRedisTemplate.opsForValue().get(statusId);
        if (s!=null){
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
